#!/bin/bash

set -eu

if ! [ -x "$(command -v java)" ]; then
  if ! [ -x "$(command -v "$JAVA_HOME/bin/java")" ]; then
    echo 'Error: java is not installed.' >&2
    exit 1
  fi
fi

if ! [ -x "$(command -v perl)" ]; then
    echo 'Error: perl is not installed.' >&2
    exit 1
fi

EVENT=
INPUT=
OUTPUT=
FORMAT=
AGG=

usage() {
  echo
  echo "Usage: $0 [options]"
  echo
  echo "options:"
  echo "  -e [ cpu | alloc ] default cpu"
  echo "  -i input-file-path"
  echo "  -o output-file-path"
  echo "  -f [ collapsed | html | svg | text ] default collapsed"
  echo "  -a [ count | sum ] default count"
  echo
  echo "examples:"
  echo "  bash jfrparser.sh -e cpu -i 1.jfr -o 1.txt"
  echo "  bash jfrparser.sh -e cpu -i 1.jfr -o 1.svg"
  echo "  bash jfrparser.sh -e cpu -i 1.jfr -o 1.data -f svg"
  echo "  bash jfrparser.sh -e cpu -i 1.jfr -o 1.data -f collapsed"
  echo
  exit 1
} >&2

while [ $# -gt 0 ]; do
  case $1 in
  -h | "-?")
    usage
    ;;
  -e)
    EVENT="$2"
    shift
    ;;
  -i)
    INPUT="$2"
    shift
    ;;
  -o)
    OUTPUT="$2"
    shift
    ;;
  -f)
    FORMAT="$2"
    shift
    ;;
  -a)
    AGG="$2"
    shift
    ;;
  -*)
    error "Unrecognized option: $1"
    usage
    ;;
  esac
  shift
done

if [[ $OUTPUT == *"svg" ]]; then
    FORMAT="svg"
elif [[ $OUTPUT == *"fold" ]]; then
    FORMAT="collapsed"
fi

TO_SVG=0
OUTPUT_FILE=$OUTPUT
if [ "$FORMAT" = "svg" ]; then
    FORMAT="collapsed"
    TO_SVG=1
    OUTPUT="$OUTPUT.collapsed"
fi

if [ ! -f "$INPUT" ]; then
    echo "input file [$INPUT] does not exist."
    exit 1
fi

DIR=$( cd "$(dirname "${BASH_SOURCE[0]}")" && pwd);
cd $DIR
java -cp standalone-1.2.0-SNAPSHOT.jar com.alibaba.profiing.visualizer.Main -e "$EVENT" -i "$INPUT" -o "$OUTPUT" -f "$FORMAT" -a "$AGG"

if [[ $TO_SVG == 1 ]]; then
    cat $OUTPUT | FlameGraph-1.0/flamegraph.pl > "$OUTPUT_FILE"
    rm -f "$OUTPUT.collapsed"
fi
